package com.cyys.modules.core.sysParam;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyys.common.redis.RedisUtil;
import com.cyys.modules.system.model.param.ParamRegion;
import com.cyys.modules.system.service.param.ParamRegionService;

import java.util.List;

public class ParamRegionUtil {

	public static void initParamRegion(ParamRegionService paramRegionService) throws Exception{
		if(RedisUtil.hSize(RedisConstants.PARAM_REGION_MAP) > 0){
			RedisUtil.delete(RedisConstants.PARAM_REGION_MAP);
			RedisUtil.delete(RedisConstants.PARAM_REGION_CODE_MAP);
		}
		QueryWrapper<ParamRegion> qw = new QueryWrapper();
		qw.orderByAsc("sort");
		List<ParamRegion> paramRegionList = paramRegionService.listAll(qw);
		for (ParamRegion paramRegion : paramRegionList) {
			RedisUtil.hPut(RedisConstants.PARAM_REGION_MAP, paramRegion.getId(), paramRegion);
			RedisUtil.hPut(RedisConstants.PARAM_REGION_CODE_MAP, paramRegion.getCityCode(), paramRegion);
			if(paramRegion.getLevel()!=3){
				ParamRegion newRegion= new ParamRegion();
				newRegion.setId(paramRegion.getId());
				newRegion.setCityCode(paramRegion.getCityCode());
				newRegion.setShortName(paramRegion.getShortName());
				List<ParamRegion> list= paramRegionService.listByParentId(paramRegion.getId());
				newRegion.setChildren(null); //空和[]意义不一样
				if(list!=null && list.size()>0){
					newRegion.setChildren(list);
				}
				RedisUtil.hPut(RedisConstants.PARAM_REGION_MAP_WITH_CHILDREN, paramRegion.getCityCode(), newRegion);
			}
		}
	}

	public static ParamRegion getParamRegionMap(String regionId) {
		return (ParamRegion)RedisUtil.hGet(RedisConstants.PARAM_REGION_MAP, regionId);
	}

	public static ParamRegion getParamRegionCodeMap(String regionCode) {
		return (ParamRegion)RedisUtil.hGet(RedisConstants.PARAM_REGION_CODE_MAP, regionCode);
	}

	/**
	 * 根据adCode查询地市/区县（带子列表）
	 * @param adCode
	 * @return
	 */
	public static ParamRegion getParamRegionWithChildren(String adCode) {
		return (ParamRegion) RedisUtil.hGet(RedisConstants.PARAM_REGION_MAP_WITH_CHILDREN, adCode);
	}
}
